<template>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" center :width="dialogWidth" @close="handleDialogCancel()"
        destroy-on-close>
        <el-form :model="state.form" label-width="120px" :rules="rules" ref="ruleFormRef">

            <el-form :model="state.form" label-width="120px" :inline="true" :rules="rules" ref="ruleFormRef">
                <el-form-item label="类型" prop="type">
                    <el-radio-group v-model="state.form.type">
                        <el-radio-button :label="0">菜单</el-radio-button>
                        <el-radio-button :label="1">按钮</el-radio-button>
                        <el-radio-button :label="2">外链</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="父级" prop="parentId">
                    <el-tree-select v-model="state.form.parentId" :data="treeData" check-strictly />
                </el-form-item>
            </el-form>

            <el-form-item label="名称" prop="title">
                <el-input v-model="state.form.title" placeholder="请选择菜单名称" />
            </el-form-item>
            <el-form-item label="路由" prop="path">
                <el-input v-model="state.form.path" placeholder="请选择路由地址" />
            </el-form-item>

            <el-form-item label="组件" prop="component">
                <el-input v-model="state.form.component" placeholder="请输入组件">
                </el-input>
            </el-form-item>
            <el-form-item label="重定向" prop="redirect">
                <el-input v-model="state.form.redirect" placeholder="重定向地址" />
            </el-form-item>

            <el-form :model="state.form" label-width="120px" :inline="true" :rules="rules" ref="ruleFormRef">
                <el-form-item label="图标" prop="icon">

                    <div class="select_icon">
                        <el-input v-model="state.form.icon" @click="selectIcon" placeholder="点击选择图标">
                            <template #prepend>
                                <el-icon :size="22">
                                    <component :is="state.form.icon"></component>
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                </el-form-item>

                <el-form-item label="排序" prop="icon">
                    <el-input-number v-model="state.form.sort" :min="0" controls-position="right" />
                </el-form-item>
            </el-form>


            <el-form :model="state.form" label-width="120px" :inline="true" :rules="rules" ref="ruleFormRef">
                <el-form-item label="隐藏" prop="hidden">
                    <el-radio-group v-model="state.form.hidden">
                        <el-radio :label="false" border>否</el-radio>
                        <el-radio :label="true" border>是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" prop="active">
                    <el-radio-group v-model="state.form.active">
                        <el-radio :label="false" border>禁用</el-radio>
                        <el-radio :label="true" border>激活</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleDialogCancel()">关闭</el-button>
                <el-button type="primary" @click="handleDialogConfirm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <IconPicker @dialog-close="iconDialog = false" v-if="iconDialog" :dialog-visible="iconDialog" @get-icon="getIcon" />
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { list, remove, add, edit, menuAll } from '@/api/menu'
import { ElMessage, ElTable } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { dialogAutoWidth } from '@/utils/dialog'
import IconPicker from '@/components/IconPicker/index.vue'

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    title: [{ required: true, message: "名称不能为空", trigger: 'blur' }],
    path: [{ required: true, message: "路由不能为空", trigger: 'blur' }],
    component: [{ required: false, message: "组件不能为空", trigger: 'blur' }],
    redirect: [{ required: false, message: "重定向地址不能为空", trigger: 'blur' }, { pattern: /^[a-zA-Z0-9_-]{1,200}$/, message: '请输入组件的重定向地址' }],
    active: [{ required: true, message: "状态不能为空", trigger: 'blur' }],
    parentId: [{ required: true, message: "父级不能为空", trigger: 'change' }],
})

let dialogWidth = ref("30%")
// 生命周期
onMounted(() => {
    getWindowResize()
    getTenantAll(null);
})
// 获取屏幕尺寸
const getWindowResize = function () {
    dialogWidth.value = dialogAutoWidth;
}
// 联级选择器被选中的数组对象
let tenantPids = ref<any[]>([])
// 表单对象
let state = reactive<any>({
    form: {
        id: null,
        parentId: 0,
        title: "",
        path: "",
        component: "",
        icon: "",
        active: true,
        type: 0,
        hidden: false,
        redirect: "",
        sort: 0,
    },
})

// 传值
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        required: true,
        default: false,
    },
    dialogTitle: {
        type: String,
        required: true,
        default: '',
    },
    dialogData: {
        type: Object,
        default: () => { },
    },
})
// 监听
watch(() => props.dialogData, () => {
    state.form = props.dialogData;
}, { deep: true, immediate: true })

// 树形菜单
let treeData = ref()
// 获取菜单列表
let menus = ref<any[]>([])
const getTenantAll = async (params: any) => {
    let res: any = await menuAll(params);
    if (res.code == '200') {
        menus.value = res.data;
        // 递归树形结构数据
        treeData.value = transListToTreeData(menus.value, 0)
        treeData.value.unshift({ label: '顶级', value: 0, disabled: false })
    }

}

// 事件派发
const emits = defineEmits(["dialogClose", "getListData"])

// 弹框中的取消按钮事件
const handleDialogCancel = () => {
    emits("dialogClose", false)
};

// 弹出框确定按钮事件
const handleDialogConfirm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid, fields) => {
        if (valid) {
            // 初始化必要参数数据
            // initFomData();
            let res: any = {};
            if (state.form.id == null) {
                res = await add(state.form);
            } else {
                res = await edit(state.form);
            }
            if (res.code == "200") {
                ElMessage.success(res.message)
                emits('getListData')
                handleDialogCancel();
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const initFomData = () => {
    if (state.form.component != '') {
        if (state.form.component.match(new RegExp("^/.*$"))) {
            state.form.component = "@/views" + state.form.component
        } else {
            state.form.component = "@/views/" + state.form.component
        }

    }
}

// 递归数组为树形
const transListToTreeData = (list: any, rootValue: any) => {
    let arr: any[] = []
    list.forEach((item: any) => {
        if (item.parentId === rootValue) {
            const children = transListToTreeData(list, item.id)
            if (children.length) {
                item.children = children
            }
            let data = {
                label: item.title,
                value: item.id,
                disabled: !item.active,
                children: item.children,
            }
            arr.push(data)
        }
    })
    return arr
}

const iconDialog = ref(false)
const selectIcon = () => {
    iconDialog.value = true;
}
const getIcon = (e: any) => {
    state.form.icon = e;
    console.log(e);
};
</script>
<style lang="less" scoped>
.select_icon {
    display: flex;
}
</style>